using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace AppManagement.MainManagers
{
	#region using
	using DevComponents.DotNetBar;
	using AppManagement.Models;
	using AppManagement.Repositories;
	using AppManagement.Helpers;
	using AppManagement.UsersManager;
	using System.Data;
	using System.Drawing;
	using System.IO;
	#endregion

	public partial class FrmLapPHIEUDATHANG : Office2007Form
	{
		public EventHandler Handler { get; set; }
		private DataTable DataSource;
		private int PHIEUDATHANG_ID;
		private DevComponents.DotNetBar.Controls.TextBoxX txtNCC_ID;

		public FrmLapPHIEUDATHANG(int phieudathang_id = -1)
		{
			InitializeComponent();
			PHIEUDATHANG_ID = phieudathang_id;
            txtNGAY_DAT_HANG.Text = String.Format("{0:dd/MM/yyyy}", DateTime.Now);
		}

		private void FrmLapPHIEUDATHANG_Load(object sender, EventArgs e)
		{
			InitGridView();
			InitHiddenFields();
			InitDataSource();
			if (PHIEUDATHANG_ID != -1)
			{
				LoadPHIEUDATHANG();
			}
		}

		private void InitGridView()
		{
			DataGridViewTextBoxColumn objColumn = new DataGridViewTextBoxColumn
			{
				HeaderText = "ID Thiết bị",
				DataPropertyName = "THIET_BI_ID",
				Name = "THIET_BI_ID",
				Width = (int)((dtgvData.Width - dtgvData.RowHeadersWidth)*((double)1/3))
			};
			dtgvData.Columns.Add(objColumn);
			objColumn = new DataGridViewTextBoxColumn
			{
				HeaderText = "Tên thiết bị",
				DataPropertyName = "TEN_THIET_BI",
				Width = (int)((dtgvData.Width - dtgvData.RowHeadersWidth)*((double)1/3))
			};
			dtgvData.Columns.Add(objColumn);
			objColumn = new DataGridViewTextBoxColumn
			{
				HeaderText = "Số lượng đặt hàng",
				DataPropertyName = "SO_LUONG_DH",
				Name = "SO_LUONG_DH",
				Width = (int)((dtgvData.Width - dtgvData.RowHeadersWidth)*((double)1/3)) - 1
			};
			dtgvData.Columns.Add(objColumn);
		}

		public void InitHiddenFields()
		{
			txtNCC_ID = new DevComponents.DotNetBar.Controls.TextBoxX
			{
				Name = "txtNCC_ID",
				Text = ""
			};
			txtNCC_ID.Visible = false;
		}

		public void InitDataSource()
		{
			DataSource = new DataTable();
			DataSource.Columns.Add("THIET_BI_ID");
			DataSource.Columns.Add("TEN_THIET_BI");
			DataSource.Columns.Add("SO_LUONG_DH");
			DataView objTimeSheetDV = new System.Data.DataView(DataSource);
			objTimeSheetDV.AllowNew = false;
			dtgvData.AutoGenerateColumns = false;
			dtgvData.DataSource = objTimeSheetDV;
			dtgvData.ClearSelection();
		}

		private void btnChonNHACUNGCAP_Click(object sender, EventArgs e)
		{
			FrmQuanLyNHACUNGCAP frm = new FrmQuanLyNHACUNGCAP(true);
			frm.Handler += GetNHACUNGCAP;
			frm.ShowDialog();
		}

		public void GetNHACUNGCAP(object sender, EventArgs e)
		{
			var eventType = (TransferSimpleDataEvent)e;
			string[] comp = eventType.Data.Split(new char[] { '#' });
			txtNCC_ID.Text = comp[0];
			txtNHACUNGCAP.Text = comp[1];
		}


		private void btnThem_Click(object sender, EventArgs e)
		{
			FrmCapNhatCHITIETPHIEUDATHANG frm = new FrmCapNhatCHITIETPHIEUDATHANG();
			frm.Handler += GetCHITIETPHIEUDATHANG;
			frm.ShowDialog();
		}

		public void GetCHITIETPHIEUDATHANG(object sender, EventArgs e)
		{
			var eventType = (TransferSimpleDataEvent)e;
			string[] comp = eventType.Data.Split(new char[] { '#' });
			var item = THIETBIRepository.SelectByID(int.Parse(comp[0]));
			if(item != null)
			{
				DataSource.Rows.Add(item.THIET_BI_ID, item.TEN_THIET_BI, comp[1]);
			}
		}


		private void btnXoa_Click(object sender, EventArgs e)
		{
			if (DataSource.Rows.Count > 0)
			{
				DataSource.Rows.RemoveAt(dtgvData.SelectedRows[0].Index);
			}
		}

		private bool ValidateInput(ref string errorText)
		{
			if (DataSource.Rows.Count == 0)
			{
				errorText = "Danh sách hiện thời không có gì!";
				return false;
			}
			return true;
		}

		private void btnCapNhat_Click(object sender, EventArgs e)
		{
			var errorText = "";
			bool success = false;
			if (!ValidateInput(ref errorText))
			{
				MessageBoxEx.Show(errorText, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return;
			}
			if (ActionUpdate())
			{
				success = true;
			}
			if (success)
			{
				MessageBoxEx.Show("Cập nhật dữ liệu thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
			}
			else
			{
				MessageBoxEx.Show("Cập nhật dữ liệu thất bại", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		private void btnThoat_Click(object sender, EventArgs e)
		{
			this.Close();
		}

		private bool ActionUpdate()
		{
			try
			{
				DataContext.Instance.Connection.Open();
				using (var transaction = DataContext.Instance.Connection.BeginTransaction())
				{
					var phieudathang = new PHIEUDATHANG
					{
						NCC_ID = int.Parse(txtNCC_ID.Text),
						NHANVIEN_ID = GlobalVariables.g_CurrentUser.NGUOIDUNG_ID,
						NGAY_DAT_HANG = DateTime.Now,
                        DANG_XU_LY = false,
                        DA_XU_LY = false
					};
					if (PHIEUDATHANGRepository.Insert(phieudathang))
					{
                        GlobalVariables.Logger.Info("Insert phieu dat hang: true");
						for (int i = 0; i <= DataSource.Rows.Count - 1; i++)
						{
							var chitietphieudathang = new CHITIETPHIEUDATHANG
							{
								PHIEUDATHANG_ID = phieudathang.PHIEUDATHANG_ID,
								THIET_BI_ID = int.Parse(DataSource.Rows[i]["THIET_BI_ID"].ToString()),
								SO_LUONG_DH = int.Parse(DataSource.Rows[i]["SO_LUONG_DH"].ToString()),
                                DA_NHAP = 0
							};
							if (!CHITIETPHIEUDATHANGRepository.Insert(chitietphieudathang))
							{
                                GlobalVariables.Logger.Info("Insert chi tiet phieu dat hang: false");
								DataContext.Instance.Connection.Close();
								return false;
							}
                            GlobalVariables.Logger.Info("Insert chi tiet phieu dat hang: true");
						}
						transaction.Commit();
					}
					else
					{
                        GlobalVariables.Logger.Info("Insert phieu dat hang: false");
						DataContext.Instance.Connection.Close();
						return false;
					}
				}
				DataContext.Instance.Connection.Close();
				return true;
			}
			catch
			{
				DataContext.Instance.Connection.Close();
				return false;
			}
		}

		private void LoadPHIEUDATHANG()
		{
			var phieudathang = PHIEUDATHANGRepository.SelectByID(PHIEUDATHANG_ID);
			if (phieudathang != null)
			{
				txtPHIEUDATHANG_ID.Text = PHIEUDATHANG_ID.ToString();
				txtNCC_ID.Text = phieudathang.NCC_ID.ToString();
				txtNHACUNGCAP.Text = phieudathang.NHACUNGCAP.TEN_NCC;
                txtNGAY_DAT_HANG.Text = String.Format("{0:dd/MM/yyyy}", phieudathang.NGAY_DAT_HANG.Value); 
				LoadCHITIETPHIEUDATHANG(phieudathang);
			}
		}

		private void LoadCHITIETPHIEUDATHANG(PHIEUDATHANG phieudathang)
		{
			var lst = CHITIETPHIEUDATHANGRepository.SelectByPHIEUDATHANG_ID(phieudathang.PHIEUDATHANG_ID);
			if (lst.Count > 0)
			{
				foreach (var item in lst)
				{
					DataSource.Rows.Add(item.THIET_BI_ID, item.THIETBI.TEN_THIET_BI, item.SO_LUONG_DH);
				}
			}
		}

	}

}
